package com.app.push.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.app.push.Utils.UPushUtils;
import com.app.push.dao.UPushDao;
import com.app.push.model.PushUser;
import com.app.push.service.UPushService;
import com.app.sysmodule.exception.ServiceException;
import com.app.sysmodule.utils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * Created by song on 2018/1/11.
 */
public class UPushServiceImpl implements UPushService {
    @Autowired
    private UPushDao uPushDao;
    public boolean saveDeviceInfo(String deviceId, String userId, String deviceToken, String channel, String source,String type) throws ServiceException{
        try{
            PushUser pushUser = uPushDao.findUserByDeviceId(deviceId);
            if(null != pushUser && userId.equals(pushUser.getUserId()) && deviceToken.equals(pushUser.getDeviceToken())){
              return true;
            }else if(null != pushUser && (!userId.equals(pushUser.getUserId()) || !deviceToken.equals(pushUser.getDeviceToken()))){
                pushUser.setUserId(userId);
                pushUser.setDeviceId(deviceId);
                pushUser.setDeviceToken(deviceToken);
                pushUser.setChannel(channel);
                pushUser.setSource(source);
                pushUser.setIsDelete(0l);
                pushUser.setType(type);
                pushUser.setUpdateDate(new Date());
                uPushDao.update(pushUser);
                return true;
            }else {
                PushUser pushUser1 = new PushUser();
                pushUser1.setUserId(userId);
                pushUser1.setDeviceId(deviceId);
                pushUser1.setDeviceToken(deviceToken);
                pushUser1.setChannel(channel);
                pushUser1.setSource(source);
                pushUser1.setIsDelete(0l);
                pushUser1.setType(type);
                pushUser1.setCreateDate(new Date());
                pushUser1.setUpdateDate(new Date());
                uPushDao.save(pushUser1);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    public JSONObject handleGroupcast(List<String> userList, List<String> companyList, String type, String channel, String source, String display_type, String filter_type, String filter, String ticker, String title, String text, String handleType) throws ServiceException {
        String resultText = null;
        JSONObject jsonObject = new JSONObject();
        String androidRet = null;
        String iosRet = null;
       try {

           String androidAppket = PropertyUtils.getProperty("androidAppket");
           String androidAppMasterSecret = PropertyUtils.getProperty("androidAppMasterSecret");
           String iosAppket = PropertyUtils.getProperty("iosAppket");
           String iosAppMasterSecret = PropertyUtils.getProperty("iosAppMasterSecret");
           if(null != filter_type && filter_type.equals("01")){
//               //android
               UPushUtils uPushUtils = new UPushUtils(androidAppket,androidAppMasterSecret);
               String androidResult = uPushUtils.sendAndroidGroupcast01(source,channel,userList,companyList,display_type,ticker,title,text,handleType);
               //ios
               UPushUtils uPushUtils1 = new UPushUtils(iosAppket,iosAppMasterSecret);
               String iosResult = uPushUtils1.sendIOSGroupcast01(source,channel,userList,companyList,display_type,text,handleType);
                if(StringUtils.isNotEmpty(androidResult)){
                    JSONObject json = JSONObject.parseObject(androidResult);
                    if(null != json && null !=json.get("ret") && "SUCCESS".equals(json.get("ret"))){
                        androidRet = json.getString("ret");
                        jsonObject.put("androidRet",androidRet);
                    }else {
                        JSONObject jsonObject1 = (JSONObject) json.get("data");
                        String error_code = jsonObject1.getString("error_code");
                        androidRet = json.getString("ret");
                        jsonObject.put("androidRet",androidRet);
                        jsonObject.put("androidErrorCode",error_code);
                        jsonObject.put("androidErrorMsg", jsonObject1.getString("error_msg"));
                    }
                }
               if(StringUtils.isNotEmpty(iosResult)){
                   JSONObject json = JSONObject.parseObject(iosResult);
                   if(null != json && null !=json.get("ret") && "SUCCESS".equals(json.get("ret"))){
                       iosRet = json.getString("ret");
                       jsonObject.put("iosRet",iosRet);
                   }else {
                       iosRet = json.getString("ret");
                       JSONObject jsonObject1 = (JSONObject) json.get("data");
                       String error_code = jsonObject1.getString("error_code");
                       jsonObject.put("iosRet",iosRet);
                       jsonObject.put("iosErrorCode",error_code);
                       jsonObject.put("iosErrorMsg", jsonObject1.getString("error_msg"));
                   }
               }

           }else {

           }
       }catch (Exception e){
           e.printStackTrace();
           throw new ServiceException(e.getMessage());
       }
        return jsonObject;
    }

    /**
     * 根据ios、android不同类型   获取不同用户deviceToken 并分别调用发送友盟方法
     * @param appkey
     * @param appMasterSecret
     * @param token
     * @param ticker
     * @param title
     * @param text
     * @throws ServiceException
     */
    public void handleUnicast(String appkey, String appMasterSecret, String token, String ticker, String title, String text) throws ServiceException{
        try {
            UPushUtils uPushUtils = new UPushUtils(appkey,appMasterSecret);
            uPushUtils.sendAndroidUnicast(token,ticker,title,text);
            uPushUtils.sendIOSUnicast(token,text);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

//    /**
//     * 处理列播
//     * @param users
//     * @param type
//     * @param ticker
//     * @param title
//     * @param text
//     */
//    public void handleListcast(List<String> users, String type, String ticker, String title, String text) throws ServiceException{
//        try{
//            if(null == users || users.size()==0){
//                return;
//            }
//            String token = getTokenByUsers(users);
//            //安卓
//            String androidAppket = PropertyUtils.getProperty("androidAppket");
//            String appMasterSecret = PropertyUtils.getProperty("appMasterSecret");
//            UPushUtils uPushUtils = new UPushUtils(androidAppket,appMasterSecret);
//            uPushUtils.sendAndroidUnicast(type,ticker,title,text);
//        }catch (Exception e){
//            throw new ServiceException(e.getMessage());
//        }
//    }

//    /**
//     * 根据用户id获取deviceToken
//     * @param users
//     * @return
//     */
//    private String getTokenByUsers(List<String> users,String type) throws ServiceException{
//        StringBuffer token = new StringBuffer();
//        try {
//           List<String> list = uPushDao.getDeviceToken(users,type);
//           if(null != list && list.size()>0){
//
//           }
//        }catch (Exception e){
//            throw new ServiceException(e.getMessage());
//        }
//        return token;
//    }
}
